"""
用Assistant api的方式进行RAG

"""
from openai import OpenAI
import os
from dotenv import load_dotenv ,find_dotenv

_=load_dotenv(find_dotenv())

client = OpenAI(
    api_key = os.getenv("OPENAI_API_KEY"),
    base_url = os.getenv("OPENAI_API_BASE")

)
# 上传文件

file = client.files.create(
    file = open(r'E:\project\work-cood\zhihu\RAG\rag_testFile.txt',"rb"),
    purpose = "assistants"
    
)
# 创建Assistant
assistant = client.beta.assistants.create(
    instructions='你是一个问答机器人，你根据给定的知识回答用户的问题',
    model = 'gpt-4-1106-preview',
    tools = [{'type':'retrieval'}],
    file_ids = [file.id]
)
# 创建Thread
thread = client.beta.threads.create()

# 创建user Message
message = client.beta.threads.messages.create(
    thread_id = thread.id,
    role = 'user',
    content = '什么时微信公众平台'
)

# 创建Run实例 同时给Assistant 提供指令
run = client.beta.threads.runs.create(
    assistant_id = assistant.id,
    thread_id = thread.id,
    instructions = '请用中文回答问题',
)

# 等待run完成
while run.status != 'completed':
    print( run.status)
    run = client.beta.threads.runs.retrieve(
        thread_id = thread.id,
        run_id = run.id
    )
# 获取run的结果

# 获取 Run 的结果
messages = client.beta.threads.messages.list(
  thread_id=thread.id
)

# 答应结果
# 打印结果
for turn in reversed(messages.data):
    print(f"{turn.role.upper()}: "+turn.content[0].text.value)